<?php

namespace app\admin\model;

use think\Model;

class WechatMemberCard extends Model
{
    // 表名
    protected $name = 'wechat_member_card';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'date_type_text',
        'use_custom_code_text',
        'get_custom_code_mode_text',
        'can_give_friend_text',
        'need_push_on_view_text',
        'create_time_text',
        'delete_time_text'
    ];

    protected static function init()
    {
        self::beforeInsert(function ($card) {
            //图片上传到Wechat 服务器
            $wechatCard = new \app\mpbase\library\WechatCard();
            if(isset($card['logo_url'])){
                $logoResult = $wechatCard->uploadImage('./'.$card['logo_url']);
                $bgResult = $wechatCard->uploadImage('./'.$card['background_pic_url']);
                if(!isset($logoResult['url']) || !isset($bgResult['url'])){
                    $card->error = '图片上传失败';
                    return false;
                }
                $card->wechat_logo_url = $logoResult['url'];
                $card->wechat_background_pic_url = $bgResult['url'];
            }
        });
    }


    public function getCodeTypeList()
    {
        return [
            'CODE_TYPE_QRCODE' => '二维码+Code',
            'CODE_TYPE_BARCODE' => '条形码+Code',
            'CODE_TYPE_ONLY_QRCODE' => '仅二维码',
            'CODE_TYPE_TEXT' => '仅显示Code',
            'CODE_TYPE_NONE' => '无Code类型'
        ];
    }

    public function getCustomNameTypeList()
    {
        return [
            'FIELD_NAME_TYPE_CUSTOM' => '自定义',
            'FIELD_NAME_TYPE_LEVEL' => '等级',
            'FIELD_NAME_TYPE_COUPON' => '优惠券',
            'FIELD_NAME_TYPE_STAMP' => '印花',
            'FIELD_NAME_TYPE_DISCOUNT' => '折扣',
            'FIELD_NAME_TYPE_ACHIEVEMEN' => '成就',
            'FIELD_NAME_TYPE_MILEAGE' => '里程',
            'FIELD_NAME_TYPE_TIMS' => '次数',
        ];
    }

    public function getCommonIdListByKey($key)
    {
        $commonFiled =  [
            'USER_FORM_INFO_FLAG_MOBILE' => '手机号',
            'USER_FORM_INFO_FLAG_SEX' => '性别',
            'USER_FORM_INFO_FLAG_NAME' => '姓名',
            'USER_FORM_INFO_FLAG_BIRTHDAY' => '生日',
            'USER_FORM_INFO_FLAG_IDCARD' => '身份证',
            'USER_FORM_INFO_FLAG_EMAIL' => '邮箱',
            'USER_FORM_INFO_FLAG_LOCATION' => '详细地址',
            'USER_FORM_INFO_FLAG_EDUCATION_BACKGRO' => '教育背景',
            'USER_FORM_INFO_FLAG_INDUSTRY' => '行业',
            'USER_FORM_INFO_FLAG_INCOME' => '收入',
            'USER_FORM_INFO_FLAG_HABIT' => '兴趣爱好'
        ];
//        array_filter($commonFiled,function($item) use ($key){
//            preg_match("/{$key}/", $item);
//        });
        $list = [];
        foreach($commonFiled as $k => $v){
            array_push($list,['id' => $k, 'value' => $v,]);
        }
        return json(['list'=>$list]);
    }

    public function getDateTypeList()
    {
        return [
            'DATE_TYPE_FIX_TERM' => __('Date_type date_type_fix_term'),
            'DATE_TYPE_FIX_TIME_RANGE' => __('Date_type date_type_fix_time_range'),
        ];
    }

    public function getBaseInfo()
    {
        $dataInfo['type'] = $this['date_type'];
        if($this['date_type'] == 'DATE_TYPE_FIX_TERM'){
            $dataInfo['fixed_term'] = $this['fixed_term'];
            $dataInfo['fixed_begin_term'] = $this['fixed_begin_term'];
        }elseif($this['date_type'] == 'DATE_TYPE_FIX_TIME_RANGE'){
            $dataInfo['begin_timestamp'] = $this['begin_timestamp'];
            $dataInfo['end_timestamp'] = $this['end_timestamp'];
        }
        $baseInfo = [
            "color" => $this['color'],
            'logo_url' => $this['wechat_logo_url'],
//            'logo_url' => 'http://mmbiz.qpic.cn/mmbiz_png/fBEQTXj4zknrWzoRNBNw5XZKicCxrdWKGK3kgItWfSe3nXa1ibccgnyickFeagicX3ExT06GvCxRSxe1vtERWq01uw/0?wx_fmt=png',
            'brand_name' => $this['brand_name'],
            'code_type' => isset($this['code_type']) ? $this['code_type'] : '',
            'title' => $this['title'],
            'notice' => $this['notice'],
            'service_phone' => $this['service_phone'],
            'description' => $this['description'],
            'date_info' => $dataInfo,
            'sku' => [
                'quantity' => $this['quantity']
            ],
            'location_id_list' => empty($this['location_id_list']) ? [] : explode(',', $this['location_id_list']),
            'get_limit' => 1,
            'use_custom_code'=>false,
            'get_custom_code_mode'=>false,
//            'use_custom_code'=>$this['use_custom_code'],
//            'get_custom_code_mode'=>$this['get_custom_code_mode'],
            'can_give_friend' => $this['can_give_friend'] == "true",

            'custom_url_name' => $this['custom_url_name'],
            'custom_url' => $this['custom_url'],
            'custom_url_sub_title' => $this['custom_url_sub_title'],
            'custom_app_brand_user_name' => $this['custom_app_brand_user_name'].'@app',
            'custom_app_brand_pass' => $this['custom_app_brand_pass'],
            'promotion_url_name' => $this['promotion_url_name'],
            'promotion_url_sub_title' => $this['promotion_url_sub_title'],
            'promotion_url' => $this['promotion_url'],
            'promotion_app_brand_user_name' => $this['promotion_app_brand_user_name'].'@app',
            'promotion_app_brand_pass' => $this['promotion_app_brand_pass'],
            'need_push_on_view' => $this['need_push_on_view'] == "true",
        ];
        if($this['center_title'] != ''){
            $baseInfo['center_title'] = $this['center_title'];
            $baseInfo['center_sub_title'] = $this['center_sub_title'];
            $baseInfo['center_url'] = $this['center_url'];
        }
        return $baseInfo;
    }

    public function getEspecial()
    {
        $fieldCount = 0;
        $especial = [
            'background_pic_url' => $this['wechat_background_pic_url'],
//            'background_pic_url' => 'http://mmbiz.qpic.cn/mmbiz_jpg/fBEQTXj4zknrWzoRNBNw5XZKicCxrdWKGQbR9eoG0ja5rLze3mvl81KXUib5XzPiaAwv1oAVCaKMFK8icrOXsVyB6A/0?wx_fmt=jpeg',
            'supply_bonus' => $this['supply_bonus'] == "true",
            'supply_balance' => $this['supply_balance'] == "true",
            'prerogative' => $this['prerogative'],
            'discount'=>100-$this['discount']*10,
            "custom_cell1"=> json_decode($this['custom_cell1'],true),
        ];
        //积分栏位
        if($especial['supply_bonus']){
            $especial['bonus_rule'] = json_decode($this['bonus_rule'],true);
            $fieldCount++;
        }
        //储值栏位
        if($especial['supply_balance']){
            $especial['balance_rules'] = json_decode($this['balance_rules'],true);
            $fieldCount++;
        }
        //自定义栏位
        switch($fieldCount){
            case 0:
                !empty($this['custom_field3'])
                && $especial['custom_field3'] = json_decode($this['custom_field3']);
            case 1:
                !empty($this['custom_field2'])
                && $especial['custom_field2'] = json_decode($this['custom_field2']);
            case 2:
                !empty($this['custom_field1'])
                && $especial['custom_field1'] = json_decode($this['custom_field1']);
            default:
        }

        //激活方式
        switch($this['activate_type']){
            case 'auto':
                $especial['auto_activate'] = $this['auto_activate'] == "true";
                break;
            case 'url':
                $especial['auto_activate'] = $this['auto_activate'] == "true";
                $especial['activate_url'] = $this['activate_url'];
                break;
            case 'app':
                $especial['activate_url'] = $this['activate_url'];
                $especial['activate_app_brand_user_name'] = $this['activate_app_brand_user_name'].'@app';
                $especial['activate_app_brand_pass'] = $this['activate_app_brand_pass'];
                break;
            case 'component':
                $especial['wx_activate'] = true;
                $especial['wx_activate_after_submit'] = $this['wx_activate_after_submit'] == "true";
                $especial['wx_activate_after_submit_url'] = $this['wx_activate_after_submit_url'];
                break;
//                unset($especial['auto_activate']);
        }
        return $especial;
    }

    public function getUseCustomCodeList()
    {
        return ['true' => __('Use_custom_code true'),'false' => __('Use_custom_code false')];
    }     

    public function getGetCustomCodeModeList()
    {
        return ['GET_CUSTOM_CODE_MODE_DEPOSIT' => __('Get_custom_code_mode_deposit'),'' => __('')];
    }     

    public function getCanGiveFriendList()
    {
        return ['true' => __('Can_give_friend true'),'false' => __('Can_give_friend false')];
    }     

    public function getNeedPushOnViewList()
    {
        return ['true' => __('Need_push_on_view true'),'false' => __('Need_push_on_view false')];
    }     

    public function getDateTypeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['date_type'];
        $list = $this->getDateTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getUseCustomCodeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['use_custom_code'];
        $list = $this->getUseCustomCodeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getGetCustomCodeModeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['get_custom_code_mode'];
        $list = $this->getGetCustomCodeModeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCanGiveFriendTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['can_give_friend'];
        $list = $this->getCanGiveFriendList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getNeedPushOnViewTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['need_push_on_view'];
        $list = $this->getNeedPushOnViewList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['delete_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function setCustomField1Attr($value)
    {
        if($value['name_type'] == 'FIELD_NAME_TYPE_CUSTOM')
            unset($value['name_type']);
        return json_encode($value);
    }

    public function setCustomField2Attr($value)
    {
        if($value['name_type'] == 'FIELD_NAME_TYPE_CUSTOM')
            unset($value['name_type']);
        return json_encode($value);
    }

    public function setCustomField3Attr($value)
    {
        if($value['name_type'] == 'FIELD_NAME_TYPE_CUSTOM')
            unset($value['name_type']);
        return json_encode($value);
    }

    //开卡字段设置
    public function setRequiredFormAttr($value)
    {
        if(isset($value['can_modify'])){
            $value['can_modify'] = boolval($value['can_modify']);
        }
        $value['rich_field_list'] = json_decode($value['rich_field_list'],true);
        return json_encode($value);
    }
    public function setOptionalFormAttr($value)
    {
        if(isset($value['can_modify'])){
            $value['can_modify'] = boolval($value['can_modify']);
        }
//        $value['rich_field_list'] = str_replace(PHP_EOL, '', $value['rich_field_list']);
        $value['rich_field_list'] = json_decode($value['rich_field_list'],true);
        return json_encode($value);
    }
    public function setServiceStatementAttr($value)
    {
        return json_encode($value);
    }
    public function setBindOldCardAttr($value)
    {
        return json_encode($value);
    }

    public function getRequiredFormAttr($value)
    {
        return json_decode($value,true);
    }
    public function getOptionalFormAttr($value)
    {
        return json_decode($value,true);
    }
    public function getServiceStatementAttr($value)
    {
        return json_decode($value,true);
    }
    public function getBindOldCardAttr($value)
    {
        return json_decode($value,true);
    }

    public function setCustomCell1Attr($value)
    {
        return json_encode($value);
    }

    public function setBonusRuleAttr($value)
    {
        foreach ($value as &$item) {
            $item = intval($item);
        }
        return json_encode($value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBeginTimestampAttr($value)
    {
        return strtotime($value);
    }

    protected function setEndTimestampAttr($value)
    {
        return strtotime($value);
    }

}
